//todo: remove api key from php proxy
var bebo = {
  uid : "",
  username : "",
  albums : null,
  launch : function() {
    var sessionKey = PREFS.getString("sessionKey");
    if (sessionKey != "") {
      bebo.api.sessionKey = sessionKey;
      bebo.uid = PREFS.getString("uid");
      bebo.username = PREFS.getString("username");
      bebo.ui.update.setUsername(bebo.username);
      bebo.api.getAlbums();
    } else {
      bebo.api.getAuthToken(bebo.api.callbacks.getAuthToken);}
  }
}
bebo.api = {
  authToken : "",
  sessionKey : "",
  beboLoginURL : "http://bebo.com/login.php",
  API_KEY : 'Ck41QERAWCK5Z82L6NbqyEPsYzYkHEUHDSor',
  getAuthToken : function() {
    var apiData = {'method' : 'auth.createToken'};
    bebo.util.makeRequest(apiData, bebo.api.callbacks.getAuthToken);
  },
  getSession : function() {
    var apiData = {'method' : 'auth.getSession', 'auth_token' : bebo.api.authToken};
    bebo.util.makeRequest(apiData, bebo.api.callbacks.getSession);
  },
  getUserInfo : function(fields, callback) {
    var apiData = {'method' : 'users.getInfo', 'session_key' : bebo.api.sessionKey, 'uids' : bebo.uid, 'fields' : fields};
    bebo.util.makeRequest(apiData, bebo.api.callbacks.getUserInfo(callback));
  },
  getAlbums : function() {
    var apiData = {'method' : 'photos.getAlbums', 'session_key' : bebo.api.sessionKey, 'uid' : bebo.uid};
    bebo.util.makeRequest(apiData, bebo.api.callbacks.getAlbums);
  },
  getPhotos : function(queryObj) {
    var apiData = {'method' : 'photos.get', 'session_key' : bebo.api.sessionKey};
    var typeClosure = "";
    if(queryObj['aid'] != undefined) {
      apiData['aid'] = queryObj['aid'];
      typeClosure = 'aid';
    } else if (queryObj['pids'] != undefined) {
      apiData['pids'] = queryObj['pids'];
      typeClosure = 'pids';
    }
    bebo.util.makeRequest(apiData, bebo.api.callbacks.getPhotos(typeClosure));
  },
  callbacks : {
    getAuthToken : function(response) {
      bebo.api.authToken = response.data;
      bebo.ui.showView('preAuth');
    },
    getSession : function(response) {
      sessionData = response.data;
      //  sessionData = makeJSONfromBebo(response.text); // hack waiting for bebo to fix
      bebo.api.sessionKey = sessionData['session_key'];
      PREFS.set('sessionKey',  bebo.api.sessionKey);
      bebo.uid = sessionData['uid'].toString();
      PREFS.set('uid', bebo.uid);
      bebo.api.getUserInfo('first_name', bebo.ui.update.setUsername);
      bebo.api.getAlbums();
    },
    getAlbums : function(response) {
      var albumsData = response.data;
      bebo.albums = albumsData; //todo: offload album info to client rather then server 
      bebo.ui.update.showAlbums();
      var albumPIDs = [];
      for each (album in bebo.albums)
        albumPIDs.push(album.cover_pid);
      bebo.api.getPhotos({'pids' : albumPIDs});
    },
    getPhotos : function(type) {
      return function(response) {
      var photos = response.data;
      bebo.ui.update.showPhotos(type, photos);
      }
    },
    getUserInfo : function(callback) {
      return function(response) {
        var userInfo = response.data[0];
        bebo.username = userInfo['first_name'];
        PREFS.set('username', bebo.username);
        callback(bebo.username);
      }
    }
  }
}

bebo.ui = {
  showView : function(showView) {
    var views = ['preAuth', 'postAuth', 'photosView']
    for each (var view in views) {
      curView = document.getElementById(view);
      if (showView == view)
        curView.style.display = "block";
      else if (curView.style.display != "none")
        curView.style.display = "none";
    }
  },
  action : {
    setupPostAuth : function() {
      bebo.api.getSession();
    },
    setupPhotosView : function() {
      bebo.api.getAlbums();
    },
    openAuthWindow : function() {
      bebo.ui.update.openAuthWindow();
    },
    changeAlbum : function(index, photoIDs) {
      var photoArgs = "";
      if(index==0)  //all albums
        photoArgs = "'pids':"+photoIDs;
      else
        photoArgs = "'aid':"+photoIDs;
        bebo.api.getPhotos(eval("({"+photoArgs+"})"));
    },
    logout : function() {
      PREFS.set('sessionKey', "");
      document.getElementById("nameAndLogoutSpan").style.display="none";
      bebo.launch();

    },
    upload : function() {
      domSessionKey = document.getElementById('sessionKey');
      domSessionKey.value= bebo.api.sessionKey;
      return true;
    }
  },
  update : {
    showAlbums : function() {
      var albumOptionsHTML = "";
      var allAlbumAids = [];
      for each (album in bebo.albums) {
        allAlbumAids.push(album.cover_pid);
        albumOptionsHTML += "<option value='" + album.aid + "'>" + album.name + " (" + album.size + ")</option>";
      }
      document.getElementById("albumsSelect").innerHTML = "<option value='[" + allAlbumAids + "]'>All Album Covers</option>" + albumOptionsHTML;
      bebo.ui.showView('photosView');
    },
    showPhotos : function(type, photos) {
      var photoGallery = "";
      for each (photo in photos) {
        switch (type) {
          case 'aid':
            photoGallery+="<img src='" + photo.src_small + "'/ >";
          break
          case 'pids':
            var album = bebo.util.find('cover_pid', photo.pid, bebo.albums);
            photoGallery+="<p style='clear:both'><span><img src='" + photo.src_small + "' style='float:left'/></span><ul style='list-style-type: none'><li> " + album.name + " created: " + new Date(parseInt(album.created)).toDateString() + "</li><li>Last modified: " + new Date(parseInt(album.modified)).toDateString() + "</li><li>Size : " + album.size +"</li></ul></p>";
          break;
          case 'subj_id':
          break;
        }
      }
      document.getElementById("photosGallery").innerHTML = photoGallery;
    },
    openAuthWindow : function() {
      var loginParams = "api_key=" + bebo.api.API_KEY + "&auth_token="  + bebo.api.authToken + "&popup=1&next=http://unwiredthinking.com/beboPhotosGadget/test.html"; //todo: update later to signal to parent window. Maybe iFrame
      window.open(bebo.api.beboLoginURL + '?' + loginParams, 'Bebo Authentication', 'height=225,width=680,modal=yes,alwaysRaised=yes');
      bebo.ui.showView('postAuth');
    },
    setUsername : function(username) {
      document.getElementById("username").innerHTML = username;
      document.getElementById("nameAndLogoutSpan").style.display="inline";
    }
  }
}

bebo.util = {
  makeRequest : function(data, callBack){
    var url = 'http://unwiredthinking.com/beboPhotosGadget/beboJSproxy.php5';
    var postData = gadgets.io.encodeValues(data);
    var params = {};
    params[gadgets.io.RequestParameters.POST_DATA] = postData;
    params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
    params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
    gadgets.io.makeRequest(url, callBack, params);
  },
  find : function(qKey, qValue, qArray) {
    for (var i=0, j=qArray.length; i<j; i++)
      if (qArray[i][qKey] == qValue)
          return qArray[i];
  }
}

//a hack to convert bad bebo reponse to JSON Object
function makeJSONfromBebo(fakeJSON) {
  var retStr = "{";
  var elmPairs = fakeJSON.match(/\w+=\w+/g);
  for each (var pair in elmPairs) {
    retStr += "\"" + pair.split(/=/)[0] + "\""
    retStr += " : "
    retStr += "\"" + pair.split(/=/)[1] + "\""
    retStr += ",";
   }
   retStr = retStr.slice(0,-1);
   retStr += "}";
   return eval("("+retStr+")");
}
